package pers.cj.pdos.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import pers.cj.pdos.cache.CacheData;
import pers.cj.pdos.cache.CacheRemove;
import pers.cj.pdos.entity.CustomType;
import pers.cj.pdos.entity.OrderRule;
import pers.cj.pdos.exception.CustomException;
import pers.cj.pdos.mapper.OrderRuleMapper;
import pers.cj.pdos.service.IOrderRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import pers.cj.pdos.utils.DateUtils;
import pers.cj.pdos.utils.Utils;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 核销单编号，商品编号，借出单，进货订单编号，商品模板，入库单编号，销售订单编号，销售编号,调拨单,商品套餐,借出归还单 服务实现类
 * </p>
 *
 * @author chenj
 * @since 2019-11-04
 */
@Service
public class OrderRuleServiceImpl extends ServiceImpl<OrderRuleMapper, OrderRule> implements IOrderRuleService {
    @Autowired
    OrderRuleMapper orderRuleMapper;
    @Override
    public List<OrderRule> listPage(Integer page, Integer limit,String companyId) {
        QueryWrapper<OrderRule> wrapper = new QueryWrapper<>();
        wrapper.eq("company_id",companyId);

        if (page !=null && limit != null) {
            IPage<OrderRule> iPage = orderRuleMapper.selectPage(new Page<>(page,limit), wrapper);
            return iPage.getRecords();
        } else {
            return orderRuleMapper.selectList(wrapper);
        }
    }

    @Override
    public int count(String companyId) {
        return orderRuleMapper.selectCount(new  QueryWrapper<OrderRule>().eq("company_id",companyId));
    }

    @Override
    public synchronized OrderRule getByType(String companyId, int type) {
        OrderRule orderRule = orderRuleMapper.selectOne(new QueryWrapper<OrderRule>().eq("company_id",companyId).eq("type",type));
        String dbDate = DateUtils.getDate(orderRule.getTime(),DateUtils.YYYYMMDD);
        String nowDate = DateUtils.getDate(new Date(),DateUtils.YYYYMMDD);
        if (!dbDate.equals(nowDate)) {
            //新的一天，当前编号为0
            orderRule.setCurrent(0);
            orderRule.setTime(new Date());
            orderRuleMapper.updateById(orderRule);
        }

        orderRuleMapper.addOrderRuleCurrent(companyId,type);
        return orderRule;
    }

    @Override
    public void update(OrderRule orderRule) {
        orderRuleMapper.updateById(orderRule);
    }
}
